package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.ResourceComment;
import com.lmt.entity.search.ResourceCommentSearch;
import com.lmt.repository.ResourceCommentRepository;
import com.lmt.service.ResourceCommentService;
import com.lmt.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("ResourceCommentServiceImpl")
public class ResourceCommentServiceImpl extends BaseService implements ResourceCommentService {

    private final ResourceCommentRepository resourceCommentRepository;

    @Autowired
    public ResourceCommentServiceImpl(ResourceCommentRepository resourceCommentRepository) {
        this.resourceCommentRepository = resourceCommentRepository;
    }

    @Override
    public ResultData save(ResourceComment resourceComment) {
        this.resourceCommentRepository.save(resourceComment);
        if (null == resourceComment.getId()){
            return ResultUtil.newFail("评论失败");
        }
        return ResultUtil.newSuccess("评论成功");
    }

    @Override
    public ResultData getCommentByResourceId(ResourceCommentSearch resourceCommentSearch) {
        List<Object> parameters = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT rc.content, ");
        sql.append("rc.comment_time AS commentTime, ");
        sql.append("(SELECT ui.user_name FROM user_info AS ui WHERE ui.id = rc.observer_id) AS observer ");
        sql.append("FROM resource_comment AS rc ");
        sql.append("WHERE rc.resource_id = ? ");
        parameters.add(resourceCommentSearch.getResourceId());
        sql.append("GROUP BY rc.comment_time DESC ");
        Map<String, Object> result = this.paginationSearch(sql, resourceCommentSearch, parameters);
        return ResultUtil.newSuccess(result);
    }
}
